package com.talent.service.iot.mqtt.codec.decoder;

import com.talent.service.iot.mqtt.model.entity.TlTopic;
import com.talent.service.iot.mqtt.model.fix.TlMqttFixedHead;
import com.talent.service.iot.mqtt.model.payload.TlMqttSubscribePayload;
import com.talent.service.iot.mqtt.model.request.TlMqttSubscribeReq;
import com.talent.service.iot.mqtt.model.variable.TlMqttSubscribeVariableHead;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.mqtt.MqttMessageType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName：TlConnectDecoder
 * @Author: hszhou
 * @Date: 2024/11/30 15:12
 * @Description: 订阅消息解码器
 */
@Component
public class TlMqttSubscribeDecoder {

    private static final  Logger logger = LoggerFactory.getLogger(TlMqttSubscribeDecoder.class);

    public TlMqttSubscribeReq build(ByteBuf buf, int remainingLength){
        TlMqttFixedHead fixedHead = decodeFixedHeader( remainingLength);
        TlMqttSubscribeVariableHead variableHead = decodeVariableHeader(buf);
        TlMqttSubscribePayload payload = decodePayLoad(buf);
        return new TlMqttSubscribeReq(fixedHead,variableHead,payload);
    }
    TlMqttFixedHead decodeFixedHeader(int remainingLength) {
        TlMqttFixedHead fixedHead =new TlMqttFixedHead();
        fixedHead.setMessageType(MqttMessageType.SUBSCRIBE);
        fixedHead.setLength(remainingLength);
        return fixedHead;
    }


    TlMqttSubscribeVariableHead decodeVariableHeader(ByteBuf buf) {
        int messageId = buf.readUnsignedShort();

        return TlMqttSubscribeVariableHead.of(messageId);
    }


    TlMqttSubscribePayload decodePayLoad(ByteBuf buf) {

        int i = buf.readableBytes();
        if(i==0){
            logger.error("no subscribe topic");
            return null;
        }
        TlMqttSubscribePayload payload = new TlMqttSubscribePayload();
        List<TlTopic> topics = new ArrayList<>();
        StringBuffer sb= new StringBuffer();
        while (buf.readableBytes()!=0){
            TlTopic topic = new TlTopic();
            int topicAFilterLength = buf.readUnsignedShort();
            byte[] topicAFilter=new byte[topicAFilterLength];
            buf.readBytes(topicAFilter);
            String topicAFilterStr = new String(topicAFilter);
            short qos = buf.readUnsignedByte();
            topic.setName(topicAFilterStr);
            topic.setQos(qos);
            topics.add(topic);
            sb.append(topicAFilterStr+" ");

        }
        payload.setTopics(topics);
        logger.debug("parse  payload is【{}】",sb);
        return payload;
    }
}
